<?php

namespace app\admin\model;
use app\common\model\Grade as GradeModel;
use app\common\model\User as UserModel;

/**
 * 用户等级
 * Class Grade
 * @package app\admin\model
 */
class Grade extends GradeModel
{
    /**
     * 追加字段
     * @var array
     */
    protected $append = [
        
    ];

    /**
     * 新增记录
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function add($data)
    {
        if (!$this->validateForm($data)) {
            return false;
        }
        return $this->exists(false)->save($data);
    }

    /**
     * 编辑记录
     * @param $data
     * @return false|int
     */
    public function edit($data)
    {
        if (!$this->validateForm($data, 'edit')) {
            return false;
        }
        return $this->exists(true)->save($data) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete($grade_id)
    {
        // 判断该等级下是否存在会员
        if (UserModel::checkExistByGradeId($grade_id)) {
            $this->error = '该等级下存在用户，无法删除!';
            return false;
        }
        return $this->update(['is_delete' => 1],['grade_id'=>$grade_id]);
    }

    /**
     * 校验器
     * @param $data
     * @param string $scene
     * @return bool
     */
    private function validateForm($data, $scene = 'add')
    {
        if ($scene === 'add') {
            // 需要判断等级权重是否已存在
            if (self::checkExistByWeight($data['weight'])) {
                $this->error = '等级权重已存在';
                return false;
            }
        } elseif ($scene === 'edit') {
            // 需要判断等级权重是否已存在
            if (empty($data['describes'])) {
                $this->error = '请输入会员描述';
                return false;
            }
            // 需要判断等级权重是否已存在
            if (self::checkExistByWeight($data['weight'], $data['grade_id'])) {
                $this->error = '等级权重已存在';
                return false;
            }
        }
        return true;
    }

    /**
     * 验证等级权重是否存在
     * @param int $weight 验证的权重
     * @param int $gradeId 自身的等级ID
     * @return bool
     */
    public static function checkExistByWeight($weight, $gradeId = 0)
    {
        $where = 'is_delete = 0 AND weight = '.(int)$weight;
        $model = new static;
        $gradeId > 0 && $where .= ' AND grade_id <> '.(int)$gradeId;
        
        return $model->where($where)
            ->value('grade_id');
    }
}